<template>
    <div class="carry">
        <v-navbar></v-navbar>
        <div class="carry-wrapper">
            <div>
                <head-icon :className="className" :price="price" :text="text"></head-icon>
                <div class="recharge">
                    <div class="wrapper">
                        <div class="recharge-way">
                            <div class="way-item" :class="{'select': select === 0}" @click="selectCheck(0)">
                                <i class="icon zfb"></i>
                                <span class="text">支付宝</span>
                            </div>
                            <div class="way-item" :class="{'select': select === 1}" @click="selectCheck(1)">
                                <i class="icon wx"></i>
                                <span class="text">微信支付</span>
                            </div>
                        </div>
                        <ul class="recharge-prices">
                            <li class="price-item" v-for="(v, i) in priceArr" :key="i" @click="e_selectMoney(v)">
                                <input type="radio" ref="radio" :id="radioId[i]" name="selectRadio" :disabled='selectSelf'/>
                                <label :for="radioId[i]"></label>
                                <!-- <img :src="v" width="74" heigzht="35" alt=""> -->
                                <div class="rechargeBack">
                                    <span v-text="`￥${v}`" />
                                </div>
                            </li>
                        </ul>
                        <div class="other">
                            <icon-title :iconClass="burseIcon" :text="burseInfo"></icon-title>
                            <div class="other-text">
                                <div class="o-content">
                                    <span class="name">充值金额</span>
                                    <span class="cue">(充值金额为100的整数倍)</span>
                                </div>
                                <input type="text" v-model="rechargeAmount" class="inpt-price" placeholder="￥0.00">
                            </div>
                            </div>
                            <div @click="e_pay">
                                <v-button :text="btnText"></v-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
</template>

<script>
import navbar from '@c/navbar/navbar'
import headIcon from '@c/headIcon/headIcon'
import iconTitle from '@c/iconTitle/iconTitle'
import Button from '@c/button/button'
import { mapState, mapMutations } from 'vuex'

const ZFB = 0
const WX = 1
import { vpost, sonpost, fpost, gpost, vlink } from '@api/axios'
import { tokenPost, jtpost, gtpost, tokenLink, jtget } from '@api/axiosByToken'
export default {
	name: 'Carry',
	data() {
		return {
			className: 'recharge',
			price: 0,
			text: '当前余额',
			select: ZFB, // 默认支付宝充值
			radioId: [], // 单选按钮关联id数组
			priceArr: [], //图片路径数组
			burseIcon: 'burse',
			burseInfo: '其它金额',
			btnText: '充值',
			selectSelf: false,
			selectMoney: '', //推荐金额
			rechargeAmount: '',
		}
	},
	components: {
		'v-navbar': navbar,
		'head-icon': headIcon,
		'icon-title': iconTitle,
		'v-button': Button,
	},

	computed: {
		...mapState(['wtitle', 'rback', 'signed']),
		radio(v) {
			let str = 'icon-' + v
			return str
		},
	},
	methods: {
		...mapMutations(['WTITLE', 'RBACK', 'USERSINGED']),
		// ============================================获取推荐充值金额👇=============================================//
		getPopMoney() {
			tokenPost(tokenLink.recharge.getRechargeMoney, {}).then(re => {
				if (re.status == 0) {
					this.priceArr = re.data.listMoney
					this.price = re.data.remainingSum
				}
			})
		},
		e_selectMoney(v) {
			this.selectMoney = v
		},
		// ============================================获取推荐充值金额👆=============================================//
		// 判断选择支付宝还是选择微信
		selectCheck(val) {
			if (val === ZFB) {
				this.select = ZFB
				return
			} else {
				this.select = WX
				return
			}
		},
		// 存储id数组
		_keepIdArr() {
			let arr = []
			for (let i = 0; i < this.priceArr.length; i++) {
				arr.push('img' + i)
			}
			return arr
		},
		// ============================================点击充值唤起支付👇========================================================//
		e_pay() {
			this.doSubmit()
		},
		// 提交充值金额
		doSubmit() {
			let rechargeMoney = ''
			if (this.selectMoney) {
				rechargeMoney = this.selectMoney
			} else {
				rechargeMoney = this.rechargeAmount
			}
			let subdata = {
				userId: localStorage.getItem('userId'),
				money: rechargeMoney,
			}
			if (subdata.money == '') {
				this.$Message.warning('请选择或者输入要充值的金额')
				return
			}

			tokenPost(tokenLink.recharge.submitRecharge, subdata).then(re => {
				if (re.status == 0) {
					this.select == ZFB
						? this.aliPay(re.data)
						: this.WeChatAppPay(re.data)
				}
			})
		},
		// ============================================点击充值唤起支付👆========================================================//

		// ============================================微信支付👇=======================================================//
		WeChatAppPay(orderID) {
			let getdata = {
				userId: localStorage.getItem('userId'),
				orderId: orderID,
			}
			tokenPost(tokenLink.recharge.subWithWeChat, getdata).then(re => {
				console.log(re)
				if (re.status == 0) {
					var params = {
						appId: re.data.appId,
						partnerid: re.data.partnerId, // merchant id
						prepayid: re.data.prepayId, // prepay id
						noncestr: re.data.nonceStr, // nonce
						timestamp: re.data.timeStamp, // timestamp
						sign: re.data.sign, // signed string
					}
					console.log(params)

					Wechat.sendPaymentRequest(
						params,
						function(response) {
							if (type == 'shopCar') {
								//清空购物车
								// self.shopCar.removeAll()
							}
							self.$router.push({
								path: 'success',
								query: {
									id: orderId,
									type: 'order',
									time: new Date().getTime(),
								},
							})
						},
						function(reason) {
							this.$router.push({
								path: 'collectDetail',
								query: {
									id: orderId,
									time: new Date().getTime(),
								},
							})
						},
					)
				}
			})
		},
		// ============================================微信支付👆=======================================================//

		// ============================================支付宝支付👇====================================================//
		aliPay(orderID) {
			let paydata = {
				userId: localStorage.getItem('userId'),
				orderId: orderID,
			}
			tokenPost(tokenLink.recharge.alipay, paydata).then(res => {
				this.AliAppPay(res)
			})
		},
		AliAppPay(response) {
			console.log('支付宝支付', response.data)

			Alipay.pay(
				response.data,
				res => {
					console.log('支付完成?', res)
					//支付完成
					if (res.resultStatus == '9000') {
						//跳转到支付成功
						self.$router.push({
							path: '/success',
							query: {
								id: orderId,
								type: self.isApply,
								time: new Date().getTime(),
							},
						})
					}
				},
				e => {
					console.log('支付失败?', e)
					if (e.resultStatus == '6001') {
						self.$router.replace({
							path: '/mine',
							query: {
								time: new Date().getTime(),
							},
						})
					}
				},
			)
		},
		// ============================================支付宝支付👆====================================================//
	},
	created() {
		this.radioId = this._keepIdArr()
		this.WTITLE('充值')
		this.RBACK(true)

		// 获取推荐金额
		this.getPopMoney()
	},
	watch: {
		select() {
			return this.select
		},
		selectMoney() {
			this.rechargeAmount = ''
		},
		rechargeAmount() {
			for (let i = 0; i < this.$refs.radio.length; i++) {
				this.$refs.radio[i].checked = false
			}
			this.selectMoney = ''
		},
	},
}
</script>
